/**
 * @file gjson_array.c
 * @brief json array
 * @author JakeYang <add358@gmail.com>
 * @version 0.1
 * @date 2016-03-01
 */

#include "gjson_array.h"
#include "gjson_value.h"

static void _g_json_array_print(gpointer data, gpointer t);

GJsonArray *g_json_array_parse(GJsonData *d)
{
    GJsonArray *array = g_ptr_array_new();
    GJsonValue *v = NULL;

    if (!_equal_char(d, '[')) {
        return NULL;
    }
    _forward(d, 1);

    for (_skip(d); !_equal_char(d, ']'); _skip(d)) {
        v = g_json_value_parse(d);
        if (NULL == v) {
            goto gjson_parse_array_failed;
        }
        g_ptr_array_add(array, v);

        _skip(d);
        if (_equal_char(d, ',')) {
            _forward(d, 1);
        }
    }

    if (!_equal_char(d, ']')) {
        goto gjson_parse_array_failed;
    }
    _forward(d, 1);

    return array;

gjson_parse_array_failed:
    g_json_array_free(array);
    return NULL;
}

void g_json_array_free(GJsonArray *array)
{
    if (!array) {
        return;
    }
    gint i = 0;
    for (i = 0; i < array->len; ++i) {
        g_json_value_free(g_ptr_array_index(array, i));
    }
    g_ptr_array_free(array, FALSE);
}

inline void _g_json_array_print(gpointer data, gpointer t)
{
    g_json_value_print(data, t);
}

gchar *g_json_array_print(GJsonArray *array)
{
    GJsonText *t = g_malloc0(sizeof(GJsonText));
    t->str = g_string_new_len(NULL, 512);
    GString *msg = NULL;

    g_string_append(t->str, "[");
    g_ptr_array_foreach(array, _g_json_array_print, t);
    g_string_append(t->str, "]");

    msg = t->str;
    g_free(t);
    return g_string_free(msg, FALSE);
}
